#include <string>
#include <vector>
#include <sstream>
#include <cctype>

using std::string;
using std::vector;

vector<string> SplitString(const string& s) {
    vector<string> result;
    std::stringstream ss(s);
    string token;
    while (ss >> token) {
        result.push_back(token);
    }
    return result;
}

vector<string> SplitString(const string& s, char delim) {
    vector<string> result;
    std::stringstream ss(s);
    string token;
    while (getline(ss, token, delim)) {
        if (!token.empty()) {
            result.push_back(token);
        }
    }
    return result;
}

vector<string> SplitString(const string& s, const string& delim) {
    vector<string> result;
    size_t start_pos = 0, end_pos;
    while (true) {
        end_pos = s.find(delim, start_pos);
        if (end_pos == string::npos) {
            string token = s.substr(start_pos);
            if (!token.empty()) {
                result.push_back(token);
            }
            break;    
        }
        string token = s.substr(start_pos, end_pos - start_pos);
        if (!token.empty()) {
            result.push_back(token);
        }
        start_pos = end_pos + delim.size();
    }
    return result;
}

string JoinString(const vector<string>& vs, char delim) {
    string result = "";
    for (size_t i = 0; i < vs.size(); ++i) {
        if (!result.empty()) {
            result += ' ';
        }
        result += vs[i];
    }
    return result;
}

string JoinString(vector<string>::const_iterator begin, vector<string>::const_iterator end, char delim = ' ') {
    string result = "";
    for (vector<string>::const_iterator it = begin; it != end; ++it) {
        if (!result.empty()) {
            result += ' ';
        }
        result += *it;
    }
    return result;
}

void RTrim(string& s) {
    if (s.empty()) {
        return;
    }
    size_t cntRightWhitespace = 0;
    for (size_t i = s.size() - 1; i >= 0; --i) {
        if (isspace(s[i])) {
            ++cntRightWhitespace;
        } else {
            break;
        }
    }
    s = s.substr(0, s.size() - cntRightWhitespace);
}
